const config = require('./config');
const jwt = require('jsonwebtoken');//引入token生成和验证模块
/**
 * 生成token方法
 * @param _id
 * @param username
 * @param time
 * @returns {string}
 */
const creatToken = function (_id, username) {
    const token = 'Bearer ' + jwt.sign({
        _id: _id,
        username: username
    }, config.SECRET, {expiresIn: config.tokenValidityTime})
    return token;
};


/**
 *验证token,第三个是可选参数，如果为true则为强校验，
 * 此状态下如果验证不通过会直接res返回,默认也是为强校验
 */
const verToken = function (req, res, boolean = true) {
    return new Promise((resolve, reject) => {
        let token = 'Bearer ';
        if (req.headers.hasOwnProperty('token')) {
            token = req.headers.token.split(' ')[1];
        } else {
            if (boolean) {
                res.send({
                        code: 401,
                        msg: "token不存在或已过期",
                    }
                );
            }
            return;
        }
        jwt.verify(token, config.SECRET, (err, decode) => {
                if (err) {
                    reject(err);
                    if (boolean) {
                        res.send({
                                code: 401,
                                msg: "token不存在或已过期",
                            }
                        );
                    }
                } else {
                    resolve(decode)
                    // console.log('token验证通过')
                }
            }
        )
    })
};

module.exports = {
    creatToken, verToken
};